﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VI.Chat.VIChatControl
{
    internal class ChatDataAccess
    {
        public void InsertMessage(string fromUser, string toUser, string message)
        {
            VIChatDataContext db = new VIChatDataContext();
            ChatMessage mess = new ChatMessage();
            mess.FromUser = fromUser;
            mess.ToUser = toUser;
            mess.Message = message;
            mess.SentDate = DateTime.Now;
            db.ChatMessages.InsertOnSubmit(mess);
            db.SubmitChanges();
        }

        public List<ChatMess> GetMessage(string toUser)
        {
            VIChatDataContext db = new VIChatDataContext();
            var listMessages = from m in db.ChatMessages
                               where (m.Received == false) && (m.ToUser == toUser)
                               select m;

            List<ChatMess> li = new List<ChatMess>();
            
            foreach (ChatMessage mess in listMessages)
            {
                mess.Received = true;
                li.Add(new ChatMess(mess.FromUser, mess.ToUser, mess.Message));
            }
            db.SubmitChanges();

            return li;                   
        }
    }
}
